export default {
  state: {
    // 初始化用户信息（从 localStorage 读取，避免刷新丢失）
    userInfo: JSON.parse(localStorage.getItem("user")) || null,
    token: localStorage.getItem("token") || "",
  },
  mutations: {
    // 设置用户信息（登录成功时调用）
    SET_USER_INFO(state, userInfo) {
      state.userInfo = userInfo;
      localStorage.setItem("user", JSON.stringify(userInfo));
    },
    SET_TOKEN(state, token) {
      state.token = token;
      localStorage.setItem("token", token);
    },
    CLEAR_USER_INFO(state) {
      state.userInfo = null;
      state.token = "";
      localStorage.removeItem("user");
      localStorage.removeItem("token");
    },
  },
  actions: {
    // 登录动作（可在这里处理登录请求，也可在组件中处理）
    login({ commit }, { token, userInfo }) {
      commit("SET_TOKEN", token);
      commit("SET_USER_INFO", userInfo);
    },
    logout({ commit }) {
      commit("CLEAR_USER_INFO");
    },
    // 调用方法,还必须指定对应的参数名
    setUser({ commit }, { userInfo }) {
      commit("SET_USER_INFO", userInfo);
    },
  },
  getters: {
    // 简化组件中获取用户信息的写法
    isLogin: (state) => !!state.userInfo,
    isAdminRole: (state) => state.userInfo && state.userInfo.role === "admin",
    isAdmin: (state) => {
      return (
        state.userInfo &&
        state.userInfo.username === "admin" &&
        state.userInfo.role === "admin"
      );
    },
    user: (state) => state.userInfo,
  },
};
